import { Injectable } from '@nestjs/common'
import { GetAccessTokenDto } from './dto/get-access-token.dto'
import { GetPhoneNumberDto, GetPhoneNumberQuery } from './dto/get-phone-number.dto'
import { GetCodeSessionDto } from './dto/get-code-session.dto'
import axios from 'axios'
import { RedisService } from '@/redis/redis.service'

@Injectable()
export class WxApiService {
  constructor(private readonly redisService: RedisService) {}

  async getPhoneNumber(dto: GetPhoneNumberDto) {
    const token_res = await this.getAccessTokenRedis()

    if (token_res.access_token) {
      const res = await axios.post(
        `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${token_res.access_token}`,
        dto,
      )
      return res.data
    } else {
      throw new Error('获取失败')
    }
  }

  async getCodeSession(dto: GetCodeSessionDto) {
    const res = await axios.get(
      `https://api.weixin.qq.com/sns/jscode2session?appid=${dto.appid}&secret=${dto.secret}&js_code=${dto.js_code}&grant_type=${dto.grant_type}`,
    )
    return res.data
  }

  async getAccessTokenRedis() {
    const access_token = await this.redisService.get('access_token')
    if (access_token) {
      return {
        access_token,
      }
    } else {
      throw new Error('获取token失败')
    }
  }
}
